/**
 * Created by chenxq on 2017/12/13.
 */
import React,{PureComponent} from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Table, Card, Button ,Form ,Input ,Row ,Col ,Select ,Popconfirm ,Modal ,message ,Divider,DatePicker,Radio} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from '../TableList.less';
import {listParams,channelStatus} from '../defaultData';
import {findObjByKey ,convertLongToString} from '../../utils/index';
import {reg} from '../../utils/CheckList';
const FormItem = Form.Item;
const { Option } = Select;
const {RangePicker} = DatePicker;
const RadioGroup = Radio.Group;
@connect(state=>({
  channel:state.loan_channel
}))
@Form.create()
export default class extends PureComponent{
  state={
    pagination:{
      ...listParams,
    },
    isvisible:false,
    editObj:{},
    key:Math.random()
  }
  defaultData={
    name:'',
    address:'',
    remark:'',
    state:channelStatus[0].key,
    contactPhone:'',
    contactName:"",
    parentId:null
  }
  columns=[{
    title: '名称',
    dataIndex: 'name',
  },{
    title:'地址',
    dataIndex:'address'
  },{
    title:'联系人名称',
    dataIndex:'contactName'
  },{
    title:'联系人电话',
    dataIndex:'contactPhone'
  },{
    title:'渠道状态',
    dataIndex:'state',
    render:(state)=>{
      let obj = findObjByKey(channelStatus,state,"key");
      return obj ? obj.name : "未知"
    }
  },{
    titile:'上级渠道名称',
    dataIndex:'parentName'
  },{
    title: '创建时间',
    dataIndex: 'createdTime',
    render:(createdTime)=>{
      return createdTime? convertLongToString(createdTime) : '';
    }
  },{
    title:'更新时间',
    dataIndex:'updatedTime',
    render(updatedTime){
      return updatedTime? convertLongToString(updatedTime) : '';
    }
  },{
    title: '备注',
    dataIndex: 'remark'
  },{
    title: "操作",
    dataIndex: "id",
    render: (id,record) =>
      <div className="operations">
        <a onClick={this.showDetail.bind(this,record)}>编辑</a>
        <Divider type="vertical" />
        <Popconfirm title="确认要删除该放款渠道?" onConfirm={this.remove.bind(this,record.id)}><a>删除</a></Popconfirm>
      </div>
  }];
  showDetail=(params)=>{
    /*if(this.props.channel.loanList.length<=0){
      message.error('请先添加放款上级渠道');
      return ;
    }*/
    //this.props.form.setFieldsValue(obj);
    this.setState({
      editObj:{...params},
      isvisible:true,
      key:Math.random()
    })

  }
  remove=(id)=>{
    let _this=this;
    this.props.dispatch({
      type:'loan_channel/fetchRemove',
      payload:{id}
    }).then(jsonData=>{
      if(jsonData.result){
        message.success('删除成功',0.8,()=>{
          _this.getList();
        })
      }else{
        message.error(jsonData.msg);
      }
    })
  }
  submit=()=>{
    let _this=this;
    this.props.form.validateFieldsAndScroll((err,values)=>{
      if(!err){
        let params={};
        for(var i in values){
          if(i.indexOf('search')<0){
            params[i]=values[i];
          }
        }
        let editObj=Object.assign({},this.state.editObj,params);
        let patchType='loan_channel/fetchAdd';
        if(editObj.id){
          patchType='loan_channel/fetchEdit'
        }
        this.props.dispatch({
          type:patchType,
          payload:editObj
        }).then(jsonData=>{
          if(jsonData.result){
            message.success(`${editObj.id?'修改':'添加'}成功`,0.8,()=>{
              _this.handleCancel();
              _this.getList();
            })

          }else{
            message.error(jsonData.msg)
          }
        });
      }
    })

  }
  handleCancel=()=>{
    this.setState({
      isvisible:false
    })
  }

  handleSearch=(e)=>{
    e.preventDefault();
    let values=this.props.form.getFieldsValue();
    let params={};
    for(var i in values){
      if(i==='searchTime'){
        if(values[i] && values[i].length==2){
          params.start=new Date(values[i][0]).getTime();
          params.end=new Date(values[i][1]).getTime();
        }else{
          params.start=null;
          params.end=null;
        }
      }
      if(i.indexOf('search')>=0 && i!=='searchTime'){
        let index=i.toLowerCase().replace('search','');
        params[index]=values[i];
      }
    }
    params.current=1;
    this.setState({
      pagination:Object.assign(this.state.pagination,params)
    },()=>{
      this.getList();
    })
  }

  getList=(page={current:1})=>{
    let pagination=this.state.pagination;
    this.props.dispatch({
      type:'loan_channel/fetchList',
      payload:Object.assign({},pagination,page)
    })
    this.props.dispatch({
      type:'loan_channel/fetchLoanList',
      payload:{}
    })
  }
  renderForm=()=>{
    const { getFieldDecorator } = this.props.form;
    return (<Form onSubmit={this.handleSearch} layout="inline">
      <Row gutter={{ md: 24, lg: 24, xl: 24 }}>
        <Col md={6}>
          <FormItem label="名称" >
            {getFieldDecorator('searchName')(
              <Input placeholder="请输入名称" />
            )}
          </FormItem>
        </Col>
        <Col md={6}>
          <FormItem label="地址">
            {getFieldDecorator('searchAddress')(
              <Input placeholder="请输入地址" />
            )}
          </FormItem>
        </Col>
        <Col md={6} sm={10}>
          <FormItem label="渠道状态">
            {getFieldDecorator('searchType')(
              <Select placeholder="请选择" style={{ width: '100%' }}>
                <Option value={null}>请选择</Option>
                {
                  channelStatus.map(item=><Option key={item.key} value={item.key}>{item.name}</Option>)
                }
              </Select>
            )}
          </FormItem>
        </Col>
        <Col md={1} sm={24}>
          <FormItem >
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">查询</Button>
            </span>
          </FormItem>
        </Col>
      </Row>
    </Form>)
  }

  componentDidMount(){
    this.getList();

  }
  render(){
    let {getFieldDecorator} = this.props.form;
    let {editObj}= this.state;
    let {channel} = this.props;
    let handleValidator=function(rule,val,callback){
      if(!val){
        callback();
        return;
      }
      if(channel.loanList.findIndex(item=>item.id==val)>=0){
        callback();
      }else{
        callback('渠道不存在')
      }
    }
    return (<PageHeaderLayout title="放款渠道列表" >
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>
            {this.renderForm()}
          </div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={this.showDetail.bind(this,this.defaultData)}>
              新增放款渠道
            </Button>
          </div>
          <div style={{marginTop: "20px"}}>
            <Table rowKey="id"
                   loading={this.props.channel.loading}
                   columns={this.columns}
                   pagination={{...this.state.pagination,total:this.props.channel.total}}
                   dataSource={this.props.channel.list}
                   onChange={this.getList}
            />
          </div>
        </div>
      </Card>
      <Modal title={editObj.id ? "编辑放款渠道":"新增放款渠道"}
             onOk={this.submit}
             onCancel={this.handleCancel}
             visible={this.state.isvisible}
             key={this.state.key}
      >
        <Form className={styles.modal}>
          <div className="flex-row">
            <div className="flex1">
              <FormItem label="名称">
                {getFieldDecorator('name', {
                  initialValue:editObj.name || '',
                  rules: [{
                    required: true, message: '请输入名称'
                  }],
                })(
                  <Input placeholder='请输入名称' style={{width:"80%"}}  />
                )}
              </FormItem>
            </div>
            <div className="flex1">
              <FormItem label="渠道状态">
                {getFieldDecorator('type',{
                  initialValue: editObj.type || channelStatus[0].key,
                  rules:[{
                    required:true,
                    message:'请选择渠道状态'
                  }]
                })(
                  <Select style={{width:"80%"}}>
                    {channelStatus.map(item=><Option key={item.key} value={item.key}>{item.name}</Option>)}
                  </Select>
                )}
              </FormItem>
            </div>

          </div>
          <div className="flex-row">
            <div className="flex1">
              <FormItem label="联系人名称">
                {getFieldDecorator('contactName', {
                  initialValue:editObj.contactName || '',
                  rules:[{
                    required:true,
                    message:'请输入联系人名称'
                  }]
                })(
                  <Input placeholder='请输入联系人名称' style={{width:"80%"}}  />
                )}
              </FormItem>
            </div>
            <div className="flex1">
              <FormItem label="联系人电话">
                {getFieldDecorator('contactPhone', {
                  initialValue:editObj.contactPhone || '',
                  rules: [{
                    required: true, message: '请输入联系人电话'
                  },{pattern:reg.mobile,message:'手机号格式不正确'}],
                })(
                  <Input placeholder='请输入联系人电话' maxLength={"11"} style={{width:"80%"}}  />
                )}
              </FormItem>
            </div>
          </div>
          <div className="flex-row">
            <div className="flex1" >
              {channel.loanList.length>0 && <FormItem label="上级渠道">
                {getFieldDecorator('parentId',{
                  initialValue:editObj.parentId || '',
                  rules:[{
                    validator: handleValidator
                  }]
                })(
                  <Select style={{width:"80%"}}
                          mode="combobox"
                          placeholder="请选择"
                          optionFilterProp="children"
                          optionLabelProp="children"
                  >
                    {
                      channel.loanList.map(item=><Option value={item.id} key={item.id}>{item.name}</Option>)
                    }
                  </Select>
                )}
              </FormItem>}
            </div>
            <div className="flex1"></div>
          </div>
          <FormItem label="地址">
            {getFieldDecorator('address',{
              initialValue:editObj.address || '',
              rules:[{
                required:true,message:'请输入地址',
              }]
            })(
              <Input placeholder='请输入地址' />
            )}
          </FormItem>
          <FormItem label="备注">
            {getFieldDecorator('remark',{
              initialValue:editObj.remark || '',
            })(
              <Input.TextArea placeholder='请输入备注' style={{height:"70px"}}  />
            )}
          </FormItem>
        </Form>
      </Modal>
    </PageHeaderLayout>)
  }
}
